package com.lhstack.opensearch.utils;

import com.lhstack.opensearch.template.OpenSearchTemplate;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Description TODO
 * @Copyright: Copyright (c) 2022 ALL RIGHTS RESERVED.
 * @Author lhstack
 * @Date 2022/6/21 10:38
 * @Modify by
 */
public class VelocityUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(OpenSearchTemplate.class);

    private static final VelocityEngine VELOCITY_ENGINE = new VelocityEngine();

    private static final Pattern PATTERN = Pattern.compile("(.|\n|\r)*(?<Trim><trim>(.|\n|\r)*</trim>)(.|\n|\r)*");

    static {
        VELOCITY_ENGINE.setProperty("resource.loader.file.class", "com.lhstack.opensearch.velocity.StringResourceLoader");
    }

    public static String render(String content, Map<String, Object> params) {
        VelocityContext velocityContext = new VelocityContext(new HashMap<>(params));
        StringWriter sw = new StringWriter();
        VELOCITY_ENGINE.getTemplate(content).merge(velocityContext, sw);
        String dsl = filters(sw.getBuffer().toString());
        LOGGER.debug("queryTemplate dsl \n{}", dsl);
        return dsl;
    }

    private static String filters(String dsl) {
        Matcher matcher = PATTERN.matcher(dsl);
        if (matcher.find()) {
            String term = matcher.group("Trim");
            String str = term.substring(6, term.length() - 7);
            String s = str.strip();
            if (s.lastIndexOf(",") == s.length() - 1) {
                s = s.substring(0, s.length() - 1);
            }
            return filters(dsl.replace(term, s));
        }
        return dsl;
    }
}
